import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import Nabar from '../../conpoment/Nabar';
import styles from './index.module.css';

// 时间段接口
interface TimeSlot {
  id: string;
  time: string;
  available: number;
  isAvailable: boolean;
}

// 诊室接口
interface Room {
  id: string;
  name: string;
}

// 日期接口
interface DateItem {
  id: string;
  day: string;
  date: string;
  isToday: boolean;
  isSelected: boolean;
  isAvailable: boolean;
}

function Index() {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedDate, setSelectedDate] = useState<string>('1');
  const [selectedRoom, setSelectedRoom] = useState<string>('1');
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
  const [showConfirmModal, setShowConfirmModal] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [showSuccess, setShowSuccess] = useState<boolean>(false);

  // 获取传递的医技项目信息
  const techInfo = location.state?.tech || {
    id: 1,
    name: '双肾及肾血管彩色多普勒',
    department: '影像科',
    description: '医技检查项目',
    price: 200,
    duration: '30分钟',
    requirements: ['携带身份证', '预约单'],
    icon: '🔬'
  };

  // 日期数据
  const dates: DateItem[] = [
    { id: '1', day: '周一', date: '今日', isToday: true, isSelected: true, isAvailable: true },
    { id: '2', day: '周二', date: '29', isToday: false, isSelected: false, isAvailable: true },
    { id: '3', day: '周三', date: '30', isToday: false, isSelected: false, isAvailable: true },
    { id: '4', day: '周四', date: '31', isToday: false, isSelected: false, isAvailable: false },
    { id: '5', day: '周五', date: '1', isToday: false, isSelected: false, isAvailable: true },
    { id: '6', day: '周六', date: '2', isToday: false, isSelected: false, isAvailable: true }
  ];

  // 诊室数据
  const rooms: Room[] = [
    { id: '1', name: 'CT诊室一' },
    { id: '2', name: 'CT诊室二' }
  ];

  // 时间段数据
  const timeSlots: TimeSlot[] = [
    { id: '1', time: '08:30-09:30', available: 10, isAvailable: true },
    { id: '2', time: '09:30-10:30', available: 0, isAvailable: false },
    { id: '3', time: '10:30-11:30', available: 5, isAvailable: true },
    { id: '4', time: '14:30-15:30', available: 6, isAvailable: true },
    { id: '5', time: '15:30-16:30', available: 8, isAvailable: true },
    { id: '6', time: '16:30-17:30', available: 10, isAvailable: true }
  ];

  const handleDateSelect = (dateId: string) => {
    setSelectedDate(dateId);
  };

  const handleRoomSelect = (roomId: string) => {
    setSelectedRoom(roomId);
  };

  const handleTimeSlotSelect = (slotId: string) => {
    setSelectedTimeSlot(slotId);
    setShowConfirmModal(true);
  };

  const handleConfirm = async () => {
    setIsLoading(true);
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 保存预约数据到本地存储
    const selectedSlot = timeSlots.find(slot => slot.id === selectedTimeSlot);
    const selectedRoomName = rooms.find(room => room.id === selectedRoom)?.name;
    const selectedDateInfo = dates.find(date => date.id === selectedDate);
    
    const appointmentData = {
      id: Date.now().toString(), // 使用时间戳作为唯一ID
      title: techInfo.name,
      orderTime: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }),
      status: 'booked',
      type: 'check',
      appointmentDetails: {
        date: selectedDateInfo?.date,
        day: selectedDateInfo?.day,
        time: selectedSlot?.time,
        room: selectedRoomName,
        available: selectedSlot?.available,
        fullDate: `2020-01-01 ${selectedSlot?.time}`,
        hospital: '四川省保健院南苑',
        patient: '王小柯'
      }
    };
    
    // 获取现有的已预约数据
    const existingBooked = JSON.parse(localStorage.getItem('bookedAppointments') || '[]');
    
    // 添加新的预约数据
    const updatedBooked = [...existingBooked, appointmentData];
    
    // 保存到本地存储
    localStorage.setItem('bookedAppointments', JSON.stringify(updatedBooked));
    
    setIsLoading(false);
    setShowConfirmModal(false);
    setShowSuccess(true);
    
    // 显示成功提示2秒后跳转到医技选择页面
    setTimeout(() => {
      setShowSuccess(false);
      navigate('/medical-tech-select');
    }, 2000);
  };

  const handleCloseModal = () => {
    setShowConfirmModal(false);
  };

  const handleCloseSuccess = () => {
    setShowSuccess(false);
    navigate('/medical-tech-select');
  };

  return (
    <div className={styles.container}>
      {/* 顶部导航栏 */}
      <Nabar title="预约时间" sticky={false} />
      
      {/* 服务信息 */}
      <div className={styles.serviceInfo}>
        <div className={styles.serviceName}>{techInfo.name}</div>
        <div className={styles.serviceDate}>
          <span className={styles.calendarIcon}>📅</span>
          <span>2020年1月</span>
        </div>
      </div>

      {/* 日期选择 */}
      <div className={styles.dateSection}>
        <div className={styles.dateList}>
          {dates.map((date) => (
            <div
              key={date.id}
              className={`${styles.dateItem} ${
                selectedDate === date.id ? styles.selectedDate : ''
              } ${!date.isAvailable ? styles.unavailableDate : ''}`}
              onClick={() => date.isAvailable && handleDateSelect(date.id)}
            >
              <div className={styles.dayName}>{date.day}</div>
              <div className={styles.dayDate}>{date.date}</div>
              {date.isToday && <div className={styles.todayLabel}>今日</div>}
            </div>
          ))}
        </div>
      </div>

      {/* 诊室选择 */}
      <div className={styles.roomSection}>
        <div className={styles.sectionTitle}>请选择检查诊室</div>
        <div className={styles.roomList}>
          {rooms.map((room) => (
            <div
              key={room.id}
              className={`${styles.roomItem} ${
                selectedRoom === room.id ? styles.selectedRoom : ''
              }`}
              onClick={() => handleRoomSelect(room.id)}
            >
              {room.name}
            </div>
          ))}
        </div>
      </div>

      {/* 时间段选择 */}
      <div className={styles.timeSection}>
        <div className={styles.sectionTitle}>请选择适合您的预约时间段</div>
        <div className={styles.timeGrid}>
          {timeSlots.map((slot) => (
            <div
              key={slot.id}
              className={`${styles.timeSlot} ${
                selectedTimeSlot === slot.id ? styles.selectedTimeSlot : ''
              } ${!slot.isAvailable ? styles.unavailableSlot : ''}`}
              onClick={() => slot.isAvailable && handleTimeSlotSelect(slot.id)}
            >
              <div className={styles.timeText}>{slot.time}</div>
              <div className={styles.availableText}>
                余{slot.available}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 底部确认模态框 */}
      {showConfirmModal && (
        <div className={styles.modalOverlay} onClick={handleCloseModal}>
          <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <span className={styles.modalTitle}>确认预约</span>
              <span className={styles.closeButton} onClick={handleCloseModal}>×</span>
            </div>
            <div className={styles.modalBody}>
              <div className={styles.confirmItem}>
                <span className={styles.confirmLabel}>就诊患者：</span>
                <span className={styles.confirmValue}>王小柯</span>
              </div>
              <div className={styles.confirmItem}>
                <span className={styles.confirmLabel}>检查项目：</span>
                <span className={styles.confirmValue}>{techInfo.name}</span>
              </div>
              <div className={styles.confirmItem}>
                <span className={styles.confirmLabel}>检查诊室：</span>
                <span className={styles.confirmValue}>
                  {rooms.find(room => room.id === selectedRoom)?.name}
                </span>
              </div>
              <div className={styles.confirmItem}>
                <span className={styles.confirmLabel}>预约时间：</span>
                <span className={styles.confirmValue}>
                  2020-01-01 {timeSlots.find(slot => slot.id === selectedTimeSlot)?.time}
                </span>
              </div>
            </div>
            <div className={styles.modalFooter}>
              <button 
                className={`${styles.confirmButton} ${isLoading ? styles.loadingButton : ''}`} 
                onClick={handleConfirm}
                disabled={isLoading}
              >
                {isLoading ? (
                  <>
                    <span className={styles.loadingSpinner}></span>
                    正在预约中
                  </>
                ) : (
                  '确认'
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 成功提示覆盖层 */}
      {showSuccess && (
        <div className={styles.successOverlay} onClick={handleCloseSuccess}>
          <div className={styles.successContent} onClick={(e) => e.stopPropagation()}>
            <div className={styles.successIcon}>✓</div>
            <div className={styles.successText}>预约成功</div>
          </div>
        </div>
      )}
    </div>
  );
}

export default Index;
